import store from '../store/index.js'
/**
 * getLocationHref
 * @param {go} = [0] 
 * @description 支持小程序和H5解析路径
 * */
export function getLocationHref(opt) {
	opt = opt || {};
	const go = opt.go || 0;
	if (Object.prototype.toString.call(go) === '[object String]') {
		return go;
	}
	const params = opt.params || {};
	const pages = getCurrentPages()
	if (pages.length === 0) {
		return location.href;
	}
	const _go = pages.length - 1 + go;
	const currentPage = pages[_go < 0 ? 0 : _go]
	const url = currentPage.route
	const options = Object.assign({}, currentPage.options, params);
	const result = [];
	for (let key in options) {
		// todo
		//分享剔除手机号，防止用手机号登录
		if(key === 'mobile') {
			continue;
		}
		const value = options[key]
		result.push(`${key}=${value}`)
	}
	return `${url}?${result.join('&')}`
}
/**
 * getWxShareHref
 * @param {go} 小程序通过getCurrentPages获取的路由列表后退到的位置，或者H5中的没有域名的路径
 * @description 仅支持H5解析分享路径，回调到app
 * */
export function getWxShareHref(opt) {
	opt = opt || {};
	const go = opt.go || 0;
	const params = opt.params || {};
	let url = '';
	if (Object.prototype.toString.call(go) === '[object String]') {
		url = encodeURIComponent(go)
	} else {
		url = encodeURIComponent(getLocationHref({
			go,
			params
		}))
	}
	const platformUrl = location.origin + '/pages/app/openApp';
	return `${platformUrl}?callbackUrl=${url}`
}

export function getResolvePath(opt) {
	// #ifdef MP-WEIXIN
	return getLocationHref(opt)
	// #endif
	// #ifdef H5
	return getWxShareHref(opt)
	// #endif
}
/**
 * getCommonShareInfo
 * @description 通用分享
 * */
export function getCommonShareInfo() {
	console.log(getResolvePath())
	return {
		path: getResolvePath(),
		title: '融创服务 | 聚友趣'
	}
}
//格式化url中多余的斜杠，唉
export function resolveUrl(url) {
	if (/^data:/.test(url)) {
		return url;
	} else {
		const list = url.split('//');
		if (/^http[s]*:/.test(url)) {
			if (list.length === 2) {
				return url;
			} else {
				const _ = [];
				for (let i = 1; i < list.length; i++) {
					_.push(list[i]);
				}
				return list[0] + '//' + _.join('/');
			}
		} else {
			const _ = [];
			for (let item of list) {
				_.push(item);
			}
			return _.join('/');
		}
	}
}

/**
 * 解析h5的请求参数
 * */
export function getQueryParams(url = '') {
	// #ifdef H5
	url = url || location.href;
	// #endif
	const search = url.split('?')[1];
	if (search) {
		const list = search.split('&'),
			params = {};
		for (let item of list) {
			const kv = item.split('=');
			params[kv[0]] = kv[1];
		}
		return params;
	}
	return {}
}

//获取UUID
export function getUUID(len, radix) {
	var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	var uuid = [],
		i;
	radix = radix || chars.length;
	if (len) {
		for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
	} else {
		var r;
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | (Math.random() * 16);
				uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
			}
		}
	}
	return uuid.join('');
}

//校验登录
export const checkLogin = function(query) {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		store.dispatch('wxLogin').then((code) => {
			store.dispatch('loginByCode', { code, ...query }).then(valid => {
				resolve(valid);
			}).catch(err => {
				unLoginAction();
				reject(err)
			})
		})
		// #endif
	})
}

//未登录提示登录操作
export const unLoginAction = function() {
	uni.removeStorageSync('Authorization');
	uni.removeStorageSync('userInfo');
	store.commit('UPDATE_USERINFO', {});
	store.commit('UPDATE_LOGINSTATUS', false);
	uni.showModal({
		title: '提示',
		content: '系统检测到您当前未登录，无法完成当前操作，是否要登录？',
		showCancel: true,
		cancelText: '我拒绝',
		confirmText: '去登录',
		success(res) {
			if (res.confirm) {

				uni.setStorageSync('authorCallbackUrl', getCurrentPages()[0].$page.fullPath);
				uni.reLaunch({
					url: '/pages/personal/index',
					animationType: 'pop-in',
					animationDuration: 200
				});
			} else {
				uni.showToast({
					title: '未登录状态无法查看和执行部分操作，请在个人中心授权登录后继续',
					icon: 'none',
					duration: 5000
				});
			}
		}
	});
}

/**
 * @description 授权
 * @param {type} 授权类型 
 * */
const authorMap = { 'userLocation': '定位', 'writePhotosAlbum': '保存到相册' }
export const authorTodo = function({
	type,
	rejectText = '拒绝授权将无法执行$当前$操作,请重新授权。',
	unAuthorText = '未获得$当前$权限,请去授权。',
	success,
	reject,
	fail
}) {
	rejectText = rejectText.replace(/\$当前\$/, authorMap[type]);
	unAuthorText = unAuthorText.replace(/\$当前\$/, authorMap[type]);
	uni.authorize({
		scope: `scope.${type}`,
		success,
		fail() {
			reject && reject();
			uni.getSetting({
				success({ authSetting }) {
					const text = authSetting[`scope.${type}`] === false ? unAuthorText : rejectText;
					uni.showModal({
						title: '提示',
						content: text,
						confirmText: '去授权',
						success({ confirm }) {
							if (confirm) {
								uni.openSetting();
							}
						},
						fail
					})
				}
			})
		}
	})
}
